﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using Pampa.CRUD.Configuration;
using Pampa.CRUD.Security;
using Pampa.CRUD.UI.CustomControls;
using Pampa.WebControls;

namespace Pampa.MVC.Fluent.Crud
{
    public class EntityViewBuilder : IHtmlString 
    {
        private string _clientId;
        private readonly object _entity;
        private EntityConfiguration _config;
        private ISecurityManager _securityManager;

        public EntityViewBuilder(Type entityType)
        {
            _entity = Activator.CreateInstance(entityType);
        }

        public EntityViewBuilder(object entity)
        {
            _entity = entity;
        }

        public EntityViewBuilder ClientId(string clientId)
        {
            _clientId = clientId;
            return this;
        }

        public EntityViewBuilder Config(string entityName, ISecurityManager securityManager = null)
        {
            _config = ConfigurationManager.GetEditConfiguration(entityName);
            _securityManager = securityManager;
            return this;
        }
        
        public EntityViewBuilder Config(EntityConfig config)
        {
            config.Init();

            _config = config.Configuration;
            _securityManager = config.SecurityManager;
            return this;
        }

        public string ToHtmlString()
        {
            var entityView = new EntityView();
            entityView.ID = _clientId;
            entityView.CssClass = "entityView";
            entityView.Entity = _entity;
            entityView.Configuration = _config;
            entityView.SecurityManager = _securityManager;

            var sb = new StringBuilder();
            sb.Append(EntityView.Includes());
            sb.Append(entityView.Render());

            return sb.ToString();
        }

        public override string ToString()
        {
            return ToHtmlString();
        }
    }
}
